package util;
//若出现不能初始dbutil的错误，在db.xml中增加密码，操作出错提示使用密码后再删除密码
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.commons.dbcp.BasicDataSource;


public class DBUtil {
	private static BasicDataSource ds = new BasicDataSource();
	private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
	private static Configuration cfg; // = Configuration.configure();;
	static {
		try {
			cfg = Configuration.configure();
			Class.forName(cfg.getDriver());
			//连接数据库，一定使用连接池，即使用open()方法
			ds.setUrl(cfg.getUrl());
			ds.setDriverClassName(cfg.getDriver());
			ds.setUsername(cfg.getUsername());
			ds.setPassword(cfg.getPwd());
			
			ds.setInitialSize(cfg.getInitialSize());
			ds.setMaxActive(cfg.getMaxActive());
			ds.setMaxIdle(cfg.getMaxIdle());
			ds.setMaxWait(cfg.getMaxWait());
			ds.setValidationQuery(cfg.getValidationQuery());
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	
	public static Connection open() throws Exception{
		return ds.getConnection();
	}
	//此方法得到的不是连接池的连接
	public static Connection openInThread() throws Exception{
		Connection con = threadLocal.get();
		if(null==con){
			con=open();
			threadLocal.set(con);
		}
		return con;
	}

	public static void closeInThread(){
		Connection con=threadLocal.get();
		if(null!=con){
			try {
				con.close();//断开有异常不管了
			} catch (SQLException e) {
			}
			threadLocal.remove();
		}
	}
	
	public static void close(Connection con, Statement stm, ResultSet rs) {
		try {
			if (rs != null)
				rs.close();
		} catch (Exception e) {
		}
		try {
			if (stm != null)
				stm.close();
		} catch (Exception e) {
		}
		try {
			if (con != null)
				con.close();
		} catch (Exception e) {
		}
	}

	public static void main(String[] args) throws Exception {
		for(int i=0;i<10;i++){
			Connection con = DBUtil.open();
			System.out.println(con);
			DBUtil.close(con, null, null);
		}
	}
	
}


